<?php
//ticket_add.php - Multi-page form for Adding Incidents
//
// SiT (Support Incident Tracker) - Support call tracking system
// Copyright (C) 2010 The Support Incident Tracker Project
// Copyright (C) 2000-2009 Salford Software Ltd. and Contributors
//
// This software may be used and distributed according to the terms
// of the GNU General Public License, incorporated herein by reference.
//
//
// Author: Ivan Lucas <ivanlucas[at]users.sourceforge.net>, Tom Gerrard
// 7Oct02 INL  Added support for maintenanceid to be put into incidents table
//Modified by : Ouedarbi Mohamed (Techfree)

$permission = 5;
require ('..'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'core.php');
require (APPLICATION_LIBPATH . 'functions.inc.php');
include(APPLICATION_PLUGINPATH . 'ticket' . DIRECTORY_SEPARATOR . 'ticketlib.inc.php');

// This page requires authentication
require (APPLICATION_LIBPATH . 'auth.inc.php');

$title = $strAddIncident;

// External variables
$action = $_REQUEST['action'];
$context = cleanvar($_REQUEST['context']);
$updateid = cleanvar($_REQUEST['updateid']);
$incomingid = cleanvar($_REQUEST['incomingid']);
$query = cleanvar($_REQUEST['query']);
$siteid = cleanvar($_REQUEST['location']);
 $contactid = cleanvar($_REQUEST['contactid']);
$search_string = cleanvar($_REQUEST['search_string']);
$from = cleanvar($_REQUEST['from']);
$win = cleanvar($_REQUEST['win']);
/***********************************************************************************************************************
TICKET PLUGIN
Fixed variable type, maintid, productid, producttext.
Adding a new var $site_location + new entry in the db incident
Author: Ouedarbi Mohamed
************************************************************************************************************************/

$type = "support";
//$type = cleanvar($_REQUEST['type']);
$maintid = '2';
//$maintid = cleanvar($_REQUEST['maintid']);
$productid = '1';
//$productid = cleanvar($_REQUEST['productid']);
$producttext = 'Support Telematique';
//$producttext = cleanvar($_REQUEST['producttext']);
$site_location = cleanvar($_REQUEST['location']);
$groupid = cleanvar($_REQUEST['gid']);
/******
END ADD
******/	


// if (!empty($incomingid) AND empty($updateid)) $updateid = db_read_column('updateid', $dbTempIncoming, $incomingid);

if (empty($action) OR $action == 'showform')
{
  $pagescripts = array('scriptaculous/scriptaculous.js','AutoComplete.js');

 // Display form to get details of the actual incident
    include (APPLICATION_INCPATH . 'htmlheader.inc.php');

    echo "<h2>".icon('add', 32)." {$strAddIncident} - {$strDetails}</h2>";

	?>

    <script type="text/javascript">
    function validateForm(form)
    {
        if (form.incidenttitle.value == '')
        {
            alert(strYouMustEnterIncidentTitle);
            form.incidenttitle.focus( );
            return false;
        }

    }
    </script>

    <script type="text/javascript">
	function update_io()
	{
    if ($('ttna_waiting').checked)
    {
        $('ttnawaiting').show();
        $('ttnasolution').hide();
    }

    if ($('ttna_solution').checked)
    {
        $('ttnawaiting').hide();
        $('ttnasolution').show();

    }

    if ($('ttna_none').checked)
    {
        $('ttnawaiting').hide();
        $('ttnasolution').hide();
    }
	}
	    </script>
	<!--
/***********************************************************************************************************************
SUPPORT CENTER
Javascript for contact_drop_down select, redirect to add incident with the contact id in the url.
Author: Ouedarbi Mohamed
************************************************************************************************************************/-->
	<script type="text/javascript">
	function change_location(formulaire)
	{
		//if (formulaire.site_location.selectedIndex != "")
		location.href = formulaire.site_location.options[formulaire.site_location.selectedIndex].value;
	}	
	</script>
	
	<script type="text/javascript">	
	function change_contact(formulaire)
	{
	//if (formulaire.admincontact.selectedIndex != "")
		location.href = formulaire.admincontact.options[formulaire.admincontact.selectedIndex].value; 		
	}
	</script> 	
	
<script>
window.dhx_globalImgPath = "codebase/imgs/";
</script>
<link rel="STYLESHEET" type="text/css" href="codebase/dhtmlxcombo.css">
<script  src="codebase/dhtmlxcommon.js"></script>
<script  src="codebase/dhtmlxcombo.js"></script>
<!--/******
END ADD
******/	-->
    <?php
    echo "<form action='{$_SERVER['PHP_SELF']}?action=assign'";
    echo " method='post' id='supportdetails' name='supportdetails' onsubmit=\"return validateForm(this)\">";
    echo "<input type='hidden' name='type' value=\"{$type}\" />";
    echo "<input type='hidden' name='contactid' value=\"{$contactid}\" />";
    echo "<input type='hidden' name='productid' value=\"{$productid}\" />";
    echo "<input type='hidden' name='maintid' value=\"{$maintid}\" />";
    echo "<input type='hidden' name='siteid' value=\"{$siteid}\" />";
/***********************************************************************************************************************
SUPPORT CENTER
Javascript for contact_drop_down select, redirect to add incident with the contact id in the url.
Author: Ouedarbi Mohamed
************************************************************************************************************************/
	echo "<input type='hidden' name='location' value=\"{$site_location}\" />";
	echo "<input type='hidden' name='gid' value=\"{$groupid}\" />";
/******
END ADD
******/
    if (!empty($updateid))
    {
        echo "<input type='hidden' name='updateid' value='$updateid' />";
    }

/**
    * SiT HELPDESK VERSION
    * author Mohamed Ouedarbi
    * Function location_drop_down ( lib/function.inc.php ) same as the site_drop_down with some modification
    * return the $siteid in the url (&siteid='') / $strLocation dans Fr-fr.
*/
    echo "<table class='vertical' width='70%'>";
    echo "<tr><td><table class='mohamed' width='100%'><tr><td>";
    $contactemail = contact_email($contactid);
	echo "{$strSiteLocation} : </td>";
	echo "<td>".location_drop_down("site_location", $site_location, TRUE)."</td></tr>";
    echo "<tr><td>";
	echo "{$strContact} :</td>";
	echo "<td>".contactuser_drop_down("alfa1", "combo_zone1", TRUE, TRUE,$site_location)."</td></tr>";
	?>
	<script>
var z = dhtmlXComboFromSelect("combo_zone1");
z.enableFilteringMode(true);

</script>
<?php
/*******************************************************************************
TEST AUTOCOMPLETE USERSHI
********************************************************************************/
if ($CONFIG['ticket_contact'] =='yes')
{
echo "<tr><td><label>{$strAlternateContact}: </td><td> ";
echo "<input type='text' id='alternate_contact' size='30' maxlength='50' name='alternate_contact' />";
echo ticket_autocomplete('alternate_contact', 'contact');
echo "</label> </td></tr>";
}
/*******************************************************************************/ 
	echo "</table>";
    echo "<br>";
	
/**
	* End
*/
    echo "<table class='mohamed' width='100%'><tr><td>";
    echo "<b>{$strContactInfo} :</b>";
    echo "<br>";
    echo "<a href=\"mailto:{$contactemail}\">".icon('contact', 16, '', $contactemail)."</a>";
    echo " <strong>".contact_realname($contactid)."</strong> <span style='font-size:80%;'>(<a href='contact_edit.php?action=edit&amp;";
    echo "contact={$contactid}'>{$strEdit}</a>)</span>, ";
    echo "<br>";
    echo "<b>{$strPlace} :</b> ".contact_site($contactid) . " ";
/**
    * SiT HELPDESK VERSION
    * author Mohamed Ouedarbi
    * Function location_drop_down ( lib/function.inc.php ) same as the site_drop_down with some modification
    * return the $siteid in the url (&siteid='').
*/	
    echo "<br>";
	echo "<b>{$strService} :</b> ". contact_department($contactid) . " (".contact_county($site_location).") ";
/**
	* End
*/
     echo "<br>";
	echo "<b>{$strTel}:</b> ".contact_phone($contactid);
    echo "</td></tr></table></td>";

    echo "<td ><table class='mohamed' width='100%'>";
  //   echo icon('contract', 16) . " <strong>{$strContract} {$maintid}</strong>: ";
 //   echo strip_tags($producttext);
         if ($type == 'free')
        {
            echo "<tr><td><label>{$strServiceLevel} : </td><td>".serviceleveltag_drop_down('servicelevel',$CONFIG['default_service_level'], TRUE)."</label></td></tr>";
			echo "<tr><td><strong>{$strPriority}</strong></td><td>".priority_drop_down("priority", 1, 4, FALSE)." </td></tr>";
			echo "<tr><td><label>{$strCategory}:</td><td> ".skill_drop_down('software', 0)."</label></td></tr>";
        }
        else
        {
            $softwareproductdropdown = softwareproduct_drop_down('software', 1, $productid);
            if (!$softwareproductdropdown) $softwareproductdropdown = '-';
            echo "<tr><td><label for='software'>{$strCategory}</label></td><td>" . $softwareproductdropdown."</td></tr>";
			echo "<tr><td><strong>{$strPriority}</strong></td><td>".priority_drop_down("priority", 1, 4, FALSE)." </td></tr>";
        }


        //echo " <tr><td><label>{$strHardwareId}: </td><td><input maxlength='50' name='productversion' size='8' type='text' /></label> </td></tr>";
		//echo "<br>";
		/*******************************************************************************
TEST AUTOCOMPLETE HARDWARE ID
********************************************************************************/
if ($CONFIG['ticket_assetid'] =='yes')
{
echo "<tr><td><label>{$strHardwareId}: </td><td> ";
echo "<input type='text' id='asset_id' size='15' maxlength='50' name='asset_id' />";
echo hi_autocomplete('asset_id', 'hardware');
echo "</label> </td></tr>";
}

/*******************************************************************************/
       
 echo "</table></td></tr>";

    if (empty($updateid))
    {
        echo "<tr><td><label for='incidenttitle'>{$strIncidentTitle}</label><br />";
        echo "<input class='required' maxlength='200' id='incidenttitle' ";
        echo "name='incidenttitle' size='50' type='text' />";
        echo " <span class='required'>{$strRequired}</span></td>\n";
        echo "<td>";
		echo "</td></tr>";

        // Inventory
        $items_array[0] = '';
        $sql = "SELECT * FROM `{$dbInventory}` ";
        $sql .= "WHERE contactid='{$contactid}' ";
        $result = mysql_query($sql);
        $contact_inv_count = mysql_num_rows($result);
        while ($items = mysql_fetch_object($result))
        {
            $var = $items->name;
            if (!empty($items->identifier))
            {
                $var .= " ({$items->identifier})";
            }
            elseif (!empty($items->address))
            {
                $var .= " ({$items->address})";
            }
            $items_array[$items->id] = $var;
        }

        // Don't show inventory section if non available for contact
        if ($contact_inv_count > 0)
        {
            echo "<tr><td><label for='inventory'>{$strInventoryItems}:</label><br />";
            echo array_drop_down($items_array, 'inventory', '', '', TRUE)."</td><td></td></tr>";
        }

        // Insert pre-defined per-product questions from the database, these should be required fields
        // These 'productinfo' questions don't have a GUI as of 27Oct05
        $sql = "SELECT * FROM `{$dbProductInfo}` WHERE productid='{$productid}'";
        $result = mysql_query($sql);
        if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
        $numquestions = mysql_num_rows($result);
        $cellcount = 1;
        while ($productinforow = mysql_fetch_array($result))
        {
            if ($cellcount & 1) echo "<tr>";
            echo "<td>";
            echo "<label>{$productinforow['information']}";
            if ($productinforow['moreinformation'] != '')
            {
                echo " (<em>{$productinforow['moreinformation']}</em>)";
            }
            echo "<br />\n";
            echo "<input class='required' maxlength='50' ";
            echo "name='pinfo{$productinforow['id']}' size='70' type='text' />";
            echo " <span class='required'>{$strRequired}</span>";
            echo "</label>";
            echo "</td>";
            $cellcount++;
            if ($cellcount > $numquestions AND $numquestions & 1)
            {
                echo "<td></td></tr>";
            }
            elseif ($cellcount & 1)  echo "</tr>";
        }
        echo "<tr><td><label for='probdesc'>{$strProblemDescription}</label>".help_link('ProblemDescriptionEngineer')."<br />";
        echo "<textarea id='probdesc' name='probdesc' rows='2' cols='60' onfocus='new ResizeableTextarea(this);'></textarea></td>\n";
/***********************************************
DATE NEEDED BY
************************************************/	

	 echo "<td><strong><u>{$strPlanification}</u></strong><br />";

    echo date_needed_by('supportdetails');
    echo "</td></tr>";
/***********************************************
************************************************/
	echo "<tr><td colspan=2><label for='workarounds'>  {$strWorkAroundsAttempted}</label>".help_link('WorkAroundsAttemptedEngineer')."<br />";
       echo "<textarea id='workarounds' name='workarounds' rows='2' cols='60' onfocus='new ResizeableTextarea(this);'></textarea></td>\n";
        // echo "<td><label for ='custimpact'>{$strCustomerImpact}</label>".help_link('CustomerImpactEngineer')."<br />";
        // echo "<textarea id='custimpact' name='custimpact' rows='2' cols='60' onfocus='new ResizeableTextarea(this);'></textarea></td></tr>\n";
    }
    else
    {
        $sql = "SELECT bodytext FROM `{$dbUpdates}` WHERE id={$updateid}";
        $result = mysql_query($sql);
        if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_WARNING);
        $updaterow = mysql_fetch_array($result);
        $mailed_body_text = $updaterow['bodytext'];

        $sql="SELECT subject FROM `{$dbTempIncoming}` WHERE updateid={$updateid}";
        $result = mysql_query($sql);
        if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_WARNING);
        $updaterow = mysql_fetch_array($result);
        $mailed_subject = $updaterow['subject'];

        echo "<tr><td><label for='incidenttitle'>{$strIncidentTitle}</label><br />";
        echo "<input class='required' maxlength='200' id='incidenttitle' ";
        echo "name='incidenttitle' size='50' type='text' value=\"".htmlspecialchars($mailed_subject,ENT_QUOTES)."\" />";
        echo " <span class='required'>{$strRequired}</span></td>\n";
        echo "<td>";
        if ($type == 'free')
        {
            echo "<strong>{$strSiteSupport}</strong>: <br />";
            echo "{$strServiceLevel} ".serviceleveltag_drop_down('servicelevel',$CONFIG['default_service_level'], TRUE);
            echo " {$strSkill} ".skill_drop_down('software', 0);
        }
        else
        {
            $softwareproductdropdown = softwareproduct_drop_down('software', 1, $productid);
            if (!$softwareproductdropdown) $softwareproductdropdown = '-';
            echo "<label for='software'>{$strSkill}</label><br />" . $softwareproductdropdown;
        }
        echo "</td></tr>";

        echo "<tr><td colspan='2'>&nbsp;</td></tr>\n";
        echo "<tr><th>{$strProblemDescription}<br /><span style='font-weight: normal'>{$strReceivedByEmail}</span></th>";
        echo "<td>".parse_updatebody($mailed_body_text)."</td></tr>\n";
        echo "<tr><td class='shade1' colspan='2'>&nbsp;</td></tr>\n";
    }
	     echo "<tr><td><strong>{$strOption}</strong><br />";
/*********************************************************/
   echo  incident_option('options');
/*********************************************************/   
    echo "</td>";

    echo "<td colspan='2'>";
    echo "<strong>{$strVisibleToCustomer}</strong><br />\n";
    echo "<label><input name='cust_vis' type='checkbox'  /> {$strVisibleToCustomer}</label>";
    echo help_link('VisibleToCustomer')."<br />";
    echo "<label><input name='send_email' type='checkbox'  /> ";
    echo "{$strSendOpeningEmailDesc}</label><br />";
    echo "</table>\n";
    echo "<input type='hidden' name='win' value='{$win}' />";
    echo "<p align='center'><input name='submit' type='submit' value='{$strAddIncident}' /></p>";
    echo "</form>\n";
 include (APPLICATION_INCPATH . 'htmlfooter.inc.php');

}
elseif ($action == 'assign')
{
    include (APPLICATION_INCPATH . 'htmlheader.inc.php');
    if ($type == "support" || $type == "free")
    {
        $html .= "<h2>{$strAddIncident} - {$strAssign}</h2>";

        // Assign SUPPORT incident
        // The incident will be added to the database assigned to the current user, and then a list of engineers
        // is displayed so that the incident can be redirected

        // External vars
        $servicelevel = cleanvar($_REQUEST['servicelevel']);
        $type = cleanvar($_REQUEST['type']);
        $incidenttitle = cleanvar($_REQUEST['incidenttitle']);
        $probdesc = cleanvar($_REQUEST['probdesc']);
        $workarounds = cleanvar($_REQUEST['workarounds']);
        $probreproduction = cleanvar($_REQUEST['probreproduction']);
        $custimpact = cleanvar($_REQUEST['custimpact']);
        $other = cleanvar($_REQUEST['other']);
        $priority = cleanvar($_REQUEST['priority']);
        $software = cleanvar($_REQUEST['software']);
        $productversion = cleanvar($_REQUEST['productversion']);
        $productservicepacks = cleanvar($_REQUEST['productservicepacks']);
        $bodytext = cleanvar($_REQUEST['bodytext']);
        $cust_vis = cleanvar($_REQUEST['cust_vis']);
        $send_email = cleanvar($_REQUEST['send_email']);
        $inventory = cleanvar($_REQUEST['inventory']);

        $timetonextaction = cleanvar($_REQUEST['timetonextaction']);
        $date = cleanvar($_REQUEST['date']);
        $timeoffset = cleanvar($_REQUEST['timeoffset']);
        $timetonextaction_days = cleanvar($_REQUEST['timetonextaction_days']);
        $timetonextaction_hours = cleanvar($_REQUEST['timetonextaction_hours']);
        $timetonextaction_minutes = cleanvar($_REQUEST['timetonextaction_minutes']);
		/*****************************************/
		$alternate_contact = cleanvar($_REQUEST['alternate_contact']);
		$asset_id = cleanvar($_REQUEST['asset_id']);
		$needed_by = cleanvar($_REQUEST['needed_by']);
		$incident_option= cleanvar($_REQUEST['incident_option']);
		$solution= cleanvar($_REQUEST['solution']);
		$closingstatus= cleanvar($_REQUEST['closingstatus']);		
		/*********************************************/		

        if ($send_email == 'on')
        {
            $send_email = 1;
        }
        else
        {
            $send_email = 0;
        }
		


        // check form input
        $errors = 0;
        // check for blank contact
        if ($contactid == 0)
        {
            $errors = 1;
            $error_string .= $strYouMustSelectAcontact;
        }

        // check for blank title
        if ($incidenttitle == '')
        {
            $incidenttitle = $strUntitled;
        }

        // check for blank priority
        if ($priority == 0)
        {
            $priority = 1;
        }

        // check for blank type
        if ($type == '')
        {
            $errors = 1;
            $error_string .= $strIncidentTypeWasBlank;
        }

        if ($type == 'free' AND $servicelevel == '' )
        {
            $errors++;
            $error_string .= $strYouMustSelectAserviceLevel;
        }

        if ($errors == 0)
        {
            // add incident (assigned to current user)

            // Calculate the time to next action
            switch ($timetonextaction)
            {
                case 'none':
                    $timeofnextaction = 0;
                    break;
                case 'time':
                    $timeofnextaction = calculate_time_of_next_action($timetonextaction_days, $timetonextaction_hours, $timetonextaction_minutes);
                    break;
                case 'date':
                    $date = explode("-", $date);
                    $timeofnextaction = mktime(8 + $timeoffset, 0, 0, $date[1], $date[2], $date[0]);
                    if ($timeofnextaction < 0) $timeofnextaction = 0;
                    break;
                default:
                    $timeofnextaction = 0;
                    break;
            }
/*************************************************************************************************************************************/			
		if ($needed_by )
			{
			$incident_planned = explode("-", $needed_by);
            $date_needed_by = mktime(8 + $timeoffset, 0, 0, $incident_planned[1], $incident_planned[2], $incident_planned[0]);
                    if ($needed_by < 0) $needed_by = 0;
			}


			
			
			
switch ($incident_option)
            {
                case 'none':
					$option = "none";
                    $owner = $sit[2];
					$status = 1;
                    break;
                case 'waiting':
					$option = "waiting";				
                    $owner = 0;
					$status = 1;					
                    break;
                case 'solution':
					$option = "solution";				
                    $owner = $sit[2];
					$txtsolution = $solution;
					$status = $closingstatus;
                    break;
                default:
                    $owner = $sit[2];
					$status = 1;					
                    break;
            }
			
/*************************************************************************************************************************************/			
 			
           if ($timeofnextaction > 0)
            {
                $timetext = "Next Action Time: ";
                $timetext .= date("D jS M Y @ g:i A", $timeofnextaction);
                $timetext .= "</b>\n\n";
                $bodytext = $timetext.$bodytext;
            }

            // Set the service level the contract
            if ($servicelevel == '')
            {
                $servicelevel = servicelevel_id2tag(maintenance_servicelevel($maintid));
            }

            // Use default service level if we didn't find one above
            if ($servicelevel == '')
            {
                $servicelevel = $CONFIG['default_service_level'];
            }

            if ($CONFIG['use_ldap'])
            {
                // Attempt to update contact
                $sql = "SELECT username, contact_source FROM `{$GLOBALS['dbContacts']}` WHERE id = {$contactid}";
                $result = mysql_query($sql);
                if (mysql_error()) trigger_error(mysql_error(), E_USER_WARNING);
                $obj = mysql_fetch_object($result);
                if ($obj->contact_source == 'ldap')
                {
                	//function authenticateLDAP($username, $password, $id = 0, $user=TRUE, $populateOnly=FALSE, $searchOnEmail=FALSE)
                    authenticateLDAP($obj->username, '', $contactid, false, true, false);
                }
            }
            if ($probdesc != '') $updatetext = "[b]{$strProblemDescription}[/b]\n" . $probdesc . "" . $owner . "" . $txtsolution . "" . $status . "\n\n";
            if ($workarounds != '') $updatetext .= "[b]{$strWorkAroundsAttempted}[/b]\n" . $workarounds . "\n\n";
            if ($probreproduction != '') $updatetext .= "[b]{$strProblemReproduction}[/b]\n" . $probreproduction . "\n\n";
            if ($custimpact != '') $updatetext .= "[b]{$strCustomerImpact}[/b]\n" . $custimpact . "\n\n";
            if ($other != '') $updatetext .= "[b]{$strDetails}[/b]\n" . $other . "\n";
            // Check the service level priorities, look for the highest possible and reduce the chosen priority if needed
            $sql = "SELECT priority FROM `{$dbServiceLevels}` WHERE tag='{$servicelevel}' ORDER BY priority DESC LIMIT 1";
            $result = mysql_query($sql);
            if (mysql_error()) trigger_error(mysql_error(), E_USER_WARNING);
            list($highestpriority) = mysql_fetch_row($result);
            if ($priority > $highestpriority)
            {
                $prioritychangedmessage = " (".sprintf($strReducedPrioritySLA, priority_name($priority)).")";
                $priority = $highestpriority;
            }
	
            $sql  = "INSERT INTO `{$dbIncidents}` (title, owner, contact, priority, servicelevel, status, type, maintenanceid, ";
            $sql .= "product, softwareid, productversion, productservicepacks, opened, lastupdated, timeofnextaction) ";
			// $sql .= "product, softwareid, productversion, productservicepacks, opened, lastupdated, timeofnextaction) ";
            $sql .= "VALUES ('{$incidenttitle}', '{$owner}', '{$contactid}', '{$priority}', '{$servicelevel}', '{$status}', 'Support', '{$maintid}', ";
            $sql .= "'{$productid}', '{$software}', '{$productversion}', '{$productservicepacks}', '{$now}', '{$now}', '{$timeofnextaction}')";
            // $sql .= "'{$productid}', '{$software}', '{$productversion}', '{$productservicepacks}', '{$now}', '{$now}', '{$timeofnextaction}','{$site_location}', '{$updatetext}','{$now}')"
            $result = mysql_query($sql);
            if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);

            $incidentid = mysql_insert_id();
            $_SESSION['incidentid'] = $incidentid;

/***************************************************************
TICKET DB
***************************************************************/
            $sql  = "INSERT INTO `{$dbTicket}` (incidentid, alternate_contact, asset_id, site_location, description, date_neededby, assigned) ";
            $sql .= "VALUES ('{$incidentid}', '{$alternate_contact}', '{$asset_id}', '{$site_location}', '{$updatetext}', '{$date_needed_by}', '{$now}')";
            $result = mysql_query($sql);
            if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
			
			
			
			
			
            // Save productinfo if there is some
            $sql = "SELECT * FROM `{$dbProductInfo}` WHERE productid='{$productid}'";
            $result = mysql_query($sql);
            if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_WARNING);
            if (mysql_num_rows($result) > 0)
            {
                while ($productinforow = mysql_fetch_object($result))
                {
                    $var = "pinfo{$productinforow->id}";
                    $pinfo = cleanvar($_POST[$var]);
                    $pisql = "INSERT INTO `{$dbIncidentProductInfo}` (incidentid, productinfoid, information) ";
                    $pisql .= "VALUES ('{$incidentid}', '{$productinforow->id}', '{$pinfo}')";
                    mysql_query($pisql);
                    if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
                }
            }

            $updatetext = "{$_SESSION['syslang']['strPriority']}: [b]" . priority_name($priority, TRUE) . "[/b]";
            if (!empty($prioritychangedmessage)) $updatetext .= $prioritychangedmessage;
            $updatetext .= "\n\n" . $bodytext;
            if ($probdesc != '') $updatetext .= "[b]{$strProblemDescription}[/b]\n" . $probdesc . "\n\n";
            if ($workarounds != '') $updatetext .= "[b]{$strWorkAroundsAttempted}[/b]\n" . $workarounds . "\n\n";
            if ($probreproduction != '') $updatetext .= "[b]{$strProblemReproduction}[/b]\n" . $probreproduction . "\n\n";
            if ($custimpact != '') $updatetext .= "[b]{$strCustomerImpact}[/b]\n" . $custimpact . "\n\n";
            if ($other != '') $updatetext .= "[b]{$strDetails}[/b]\n" . $other . "\n";
            if ($cust_vis == "on") $customervisibility = 'show';
            else $customervisibility = 'hide';

            if (!empty($updateid))
            {
                // Assign existing update to new incident if we have one
                $sql = "UPDATE `{$dbUpdates}` SET incidentid='{$incidentid}', userid='{$sit[2]}' WHERE id='{$updateid}'";

                $result = mysql_query($sql);
                if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);

                $old_path = $CONFIG['attachment_fspath']. 'updates' . $fsdelim;
                $new_path = $CONFIG['attachment_fspath'] . $incidentid . $fsdelim;

                //move attachments from updates to incident
                $sql = "SELECT linkcolref, filename FROM `{$dbLinks}` AS l, ";
                $sql .= "`{$dbFiles}` as f ";
                $sql .= "WHERE l.origcolref = '{$updateid}' ";
                $sql .= "AND l.linktype = 5 ";
                $sql .= "AND l.linkcolref = f.id";
                $result = mysql_query($sql);
                if ($result)
                {
                    if (!file_exists($new_path))
                    {
                        $umask = umask(0000);
                        @mkdir($new_path, 0770);
                        umask($umask);
                    }

                    while ($row = mysql_fetch_object($result))
                    {
                        $filename = $row->linkcolref . "-" . $row->filename;
                        $old_file = $old_path . $row->linkcolref;
                        if (file_exists($old_file))
                        {
                            $rename = rename($old_file, $new_path . $filename);
                            if (!$rename)
                            {
                                trigger_error("Couldn't move file: {$file}", E_USER_WARNING);
                                $moved_attachments = FALSE;
                            }
                        }
                    }
                }
                //remove from tempincoming to prevent build up
                $sql = "DELETE FROM `{$dbTempIncoming}` WHERE updateid='$updateid'";
                mysql_query($sql);
                if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
            }
            else
            {
                // Create a new update from details entered
                $sql  = "INSERT INTO `{$dbUpdates}` (incidentid, userid, type, bodytext, timestamp, currentowner, ";
                $sql .= "currentstatus, customervisibility, nextaction) ";
                $sql .= "VALUES ('{$incidentid}', '{$sit[2]}', 'opening', '{$updatetext}', '{$now}', '{$sit[2]}', ";
                $sql .= "'1', '{$customervisibility}', '{$nextaction}')";
                $result = mysql_query($sql);
                if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
            }

            // get the service level
            // find out when the initial response should be according to the service level
            if (empty($servicelevel) OR $servicelevel==0)
            {
                // FIXME: for now we use id but in future use tag, once maintenance uses tag
                $servicelevel = maintenance_servicelevel($maintid);
                $sql = "SELECT * FROM `{$dbServiceLevels}` WHERE id='$servicelevel' AND priority='$priority' ";
            }
            else
            {
                $sql = "SELECT * FROM `{$dbServiceLevels}` WHERE tag='$servicelevel' AND priority='$priority' ";
            }

            $result = mysql_query($sql);
            if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_WARNING);
            $level = mysql_fetch_object($result);

            $targetval = $level->initial_response_mins * 60;
            $initialresponse = $now + $targetval;
/*******************************************************************************************************************************/			
			if ($date_needed_by != 0)
            {
                $date_needed_status = "planned";
            }
		else
		{
		$date_needed_status = "actionplan";
		}
/*********************************************************************************************************************************/
            // Insert the first SLA update, this indicates the start of an incident
            // This insert could possibly be merged with another of the 'updates' records, but for now we keep it seperate for clarity
            $sql  = "INSERT INTO `{$dbUpdates}` (incidentid, userid, type, timestamp, currentowner, currentstatus, customervisibility, sla, bodytext) ";
            $sql .= "VALUES ('{$incidentid}', '{$sit[2]}', 'slamet', '{$now}', '{$sit[2]}', '1', 'show', '{$date_needed_status}','')";
            mysql_query($sql);
            if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);

            // Insert the first Review update, this indicates the review period of an incident has started
            // This insert could possibly be merged with another of the 'updates' records, but for now we keep it seperate for clarity
            $sql  = "INSERT INTO `{$dbUpdates}` (incidentid, userid, type, timestamp, currentowner, currentstatus, customervisibility, sla, bodytext) ";
            $sql .= "VALUES ('{$incidentid}', '{$sit[2]}', 'reviewmet', '{$now}', '{$sit[2]}', '1', 'hide', '{$date_needed_status}','')";
            mysql_query($sql);
            if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
			
			// if ($option =="solution")
			// {
            // $sql  = "INSERT INTO `{$dbUpdates}` (incidentid, userid, type, timestamp, currentowner, currentstatus, customervisibility, sla, bodytext, needed_by) ";
            // $sql .= "VALUES ('{$incidentid}', '{$owner}', 'closing', '{$now}', '{$sit[2]}', '1', 'show', '{$date_needed_status}','{$_SESSION['syslang']['strIncidentClosed']}.','{$date_needed_by}')";
            // mysql_query($sql);
            // if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
			// }			
            if (!empty($inventory) AND $inventory != 0)
            {
                $sql = "INSERT INTO `{$dbLinks}`(linktype, origcolref, linkcolref, direction, userid) ";
                $sql .= "VALUES(7, '{$incidentid}', '{$inventory}', 'left', '{$sit[2]}')";
                mysql_query($sql);
                if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
            }

            plugin_do('incident_created');

            // Decrement free support, where appropriate
            if ($type == 'free')
            {
                decrement_free_incidents(contact_siteid($contactid));
                plugin_do('incident_created_site');
            }
            else
            {
                // decrement contract incident by incrementing the number of incidents used
                increment_incidents_used($maintid);
                plugin_do('incident_created_contract');
            }

            $html .= "<h3>{$strIncident}: $incidentid</h3>";
            $html .=  "<p align='center'>";
            $html .= sprintf($strIncidentLoggedEngineer, $incidentid);
            $html .= "</p>\n";

            $suggested_user = suggest_reassign_userid($incidentid);
            trigger('TRIGGER_INCIDENT_CREATED', array('incidentid' => $incidentid, 'sendemail' => $send_email));

            if ($CONFIG['auto_assign_incidents'])
            {
                html_redirect("ticket_add.php?action=reassign&userid={$suggested_user}&incidentid={$incidentid}");
                exit;
            }
            elseif ($option == "waiting")
			 {
			 html_redirect("ticket_add.php?action=reassign&userid={$owner}&incidentid={$incidentid}&option=waiting");
			 exit;
			 }
            elseif ($option == "solution")
			 {
			$sql = "UPDATE `{$dbIncidents}` SET status='2', closingstatus='{$status}', lastupdated='{$now}', closed='{$now}' WHERE id='{$incidentid}'";
            $result = mysql_query($sql);
            if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
			new_update($incidentid, $updatetext, $type = 'probdef', $sla = '', $userid = $sit['2'], $currentowner = $owner,
                    $currentstatus = $status, $visibility = 'hide');
			new_update($incidentid, $txtsolution, $type = 'solution', $sla = '', $userid = $sit['2'], $currentowner = $owner,
                    $currentstatus = $status, $visibility = 'hide');
			new_update($incidentid,$text = '', $type = 'slamet', $sla = 'solution', $userid = $sit['2'], $currentowner = $owner,
                    $currentstatus = $status, $visibility = 'show');
			new_update($incidentid,$_SESSION['syslang']['strIncidentClosed'], $type = 'closing', $sla = '', $userid = $sit['2'], $currentowner = $owner,
                    $currentstatus = $status, $visibility = 'unset');
			 html_redirect("ticket_add.php?action=reassign&userid={$owner}&incidentid={$incidentid}&option=closing");
			 exit;
			 }			 
			 else
            {
                echo $html;
            }

/***********************************************************************************
LIST BY GROUP SELECTED IN ADD_INCIDENT
*************************************************************************************/
			if ($groupid)
			{$arg = "AND groupid = {$groupid}";}
			else
			{$arg = "";}
			
		// $role = user_roles($sit[2]);
		switch ($role)
		{
                case '1':
					$arg2 = "";

                    break;
                case '2':
					$arg2 = "";
					
                    break;
                case '3':
					$arg2 = "AND id ={$sit[2]}";

                    break;
                default:
					$arg2 = "";	
				
                    break;
		}
            // List Engineers
            // We need a user type 'engineer' so we don't just list everybody
            // Status zero means account disabled
            $sql = "SELECT * FROM `{$dbUsers}` WHERE status!=0 {$arg2} ORDER BY realname";
            $result = mysql_query($sql);
            if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_WARNING);
            echo "<h3>{$strUsers}</h3>
            <table align='center'>
            <tr>
                <th>&nbsp;</th>
                <th>{$strName}</th>
                <th>{$strTelephone}</th>
                <th>{$strStatus}</th>
                <th>{$strMessage}</th>
                <th colspan='5'>{$strIncidentsinQueue}</th>
                <th>{$strAccepting}</th>
            </tr>";
            echo "<tr>
            <th colspan='5'></th>
            <th align='center'>{$strActionNeeded} / {$strOther}</th>";
            echo "<th align='center'>".priority_icon(4)."</th>";
            echo "<th align='center'>".priority_icon(3)."</th>";
            echo "<th align='center'>".priority_icon(2)."</th>";
            echo "<th align='center'>".priority_icon(1)."</th>";

            echo "<th></th>";
            echo "</tr>";

            $shade = 'shade2';
            while ($userrow = mysql_fetch_array($result))
            {
			

                if ($userrow['id'] == $suggested_user) $shade = 'idle';
                echo "<tr class='$shade'>";
                // display reassign link only if person is accepting or if the current user has 'reassign when not accepting' permission
                if ($userrow['accepting'] == 'Yes')
                {
                    echo "<td align='right'><a href=\"{$_SERVER['PHP_SELF']}?action=reassign&amp;userid={$userrow['id']}&amp;incidentid={$incidentid}&amp;nextaction=".urlencode($nextaction)."&amp;win={$win}\" ";
                    // if ($priority >= 3) echo " onclick=\"alertform.submit();\"";
                    echo ">{$strAssignTo}</a></td>";
                }
                elseif (user_permission($sit[2],40) OR $userrow['id'] == $sit[2])
                {
                    echo "<td align='right'><a href=\"{$_SERVER['PHP_SELF']}?action=reassign&amp;userid={$userrow['id']}&amp;incidentid={$incidentid}&amp;nextaction=".urlencode($nextaction)."&amp;win={$win}\" ";
                    // if ($priority >= 3) echo " onclick=\"alertform.submit();\"";
                    echo ">{$strForceTo}</a></td>";
                }
                else
                {
                    echo "<td class='expired'>&nbsp;</td>";
                }
                echo "<td>";

                // Have a look if this user has skills with this software
                $ssql = "SELECT softwareid FROM `{$dbUserSoftware}` ";
                $ssql .= "WHERE userid='{$userrow['id']}' AND softwareid='{$software}' ";
                $sresult = mysql_query($ssql);
                if (mysql_num_rows($sresult) >= 1)
                {
                    echo "<strong>{$userrow['realname']}</strong>";
                }
                else
                {
                    echo $userrow['realname'];
                }

                echo "</td>";
                echo "<td>".$userrow['phone']."</td>";
                echo "<td>".user_online_icon($userrow['id'])." ".userstatus_name($userrow['status'])."</td>";
                echo "<td>".$userrow['message']."</td>";
                echo "<td align='center'>";

                $incpriority = user_incidents($userrow['id']);
                $countincidents = ($incpriority['1']+$incpriority['2']+$incpriority['3']+$incpriority['4']);

                if ($countincidents >= 1) $countactive = user_activeincidents($userrow['id']);
                else $countactive = 0;

                $countdiff = $countincidents-$countactive;

                echo "$countactive / {$countdiff}</td>";
                echo "<td align='center'>".$incpriority['4']."</td>";
                echo "<td align='center'>".$incpriority['3']."</td>";
                echo "<td align='center'>".$incpriority['2']."</td>";
                echo "<td align='center'>".$incpriority['1']."</td>";

                echo "<td align='center'>";
                echo $userrow['accepting'] == 'Yes' ? $strYes : "<span class='error'>{$strNo}</span>";
                echo "</td>";
                echo "</tr>\n";
                if ($shade == 'shade2') $shade = 'shade1';
                else $shade = 'shade2';
            }
            echo "</table>";
            echo "<p align='center'>{$strUsersBoldSkills}.</p>";
        }
        else
        {
            trigger_error('User input error: '. $error_string, E_USER_ERROR);
        }
    }
    include (APPLICATION_INCPATH . 'htmlfooter.inc.php');
}
elseif ($action == 'reassign')
{
    // External variables
    $incidentid = cleanvar($_REQUEST['incidentid']);
    $uid = cleanvar($_REQUEST['userid']);
    $nextaction = cleanvar($_REQUEST['nextaction']);
    $incident_option = cleanvar($_REQUEST['option']);
	
	if ($incident_option == "closing")
	{
	include (APPLICATION_INCPATH . 'htmlheader.inc.php');
	?>
	
	<script type="text/javascript">
	function ticket_details_window(incidentid, win, rtn)
	{
		// URL = "incident.php?popup=yes&id=" + incidentid;
		// URL = application_webpath + "incident_details.php?id=" + incidentid + "&win=" + win;
		URL = "ticket_details.php?id=" + incidentid + "&win=" + win;
		if (popwin)
		{
		popwin.close();
		}
		popwin = window.open(URL, "sit_popup", "toolbar=yes,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=700,height=600");
		if (rtn == true) return popwin;
	}	
    </script>
	
	<?php
	
    echo "<h2>{$strIncidentAdded} - {$strSummary}</h2>";
    echo "<p align='center'>";
    $incidentnum = "<a href=\"javascript:ticket_details_window('$incidentid','incident{$incidentid}');\">{$strIncident} {$incidentid}</a>";
    $queuename = "<strong style='color: red'>{$strIncidentClosed}</strong>";
    $name = user_realname($uid);
    printf($strHasBeenAutoMovedToX, $incidentnum, $name, $queuename);
	include (APPLICATION_INCPATH . 'htmlfooter.inc.php');
	}
	else
	{ 

    include (APPLICATION_INCPATH . 'htmlheader.inc.php');
	?>
	
	<script type="text/javascript">
	function ticket_details_window(incidentid, win, rtn)
{
    // URL = "incident.php?popup=yes&id=" + incidentid;
    // URL = application_webpath + "incident_details.php?id=" + incidentid + "&win=" + win;
    URL = "ticket_details.php?id=" + incidentid + "&win=" + win;
    if (popwin)
    {
        popwin.close();
    }
    popwin = window.open(URL, "sit_popup", "toolbar=yes,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=700,height=600");
    if (rtn == true) return popwin;
}
    </script>

	<?php
    echo "<h2>{$strIncidentAdded} - {$strSummary}</h2>";
    echo "<p align='center'>";
    $incidentnum = "<a href=\"javascript:ticket_details_window('$incidentid','incident{$incidentid}');\">{$strIncident} {$incidentid}</a>";
    $queuename = "<strong style='color: red'>{$strActionNeeded}</strong>";
    $name = user_realname($uid);
    printf($strHasBeenAutoMovedToX, $incidentnum, $name, $queuename);
    echo help_link('AutoAssignIncidents')."</p><br /><br />";
    $userphone = user_phone($userid);
    if ($userphone!='') echo "<p align='center'>{$strTelephone}: {$userphone}</p>";
    $sql = "UPDATE `{$dbIncidents}` SET owner='$uid', lastupdated='$now' WHERE id='$incidentid'";
	mysql_query($sql);
    if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
    $sql = "UPDATE `{$dbTicket}` SET assigned='$now' WHERE incidentid='$incidentid'";
	mysql_query($sql);
    if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
    trigger('TRIGGER_INCIDENT_ASSIGNED', array('userid' => $uid, 'incidentid' => $incidentid));



    // add update
    $sql  = "INSERT INTO `{$dbUpdates}` (incidentid, userid, type, timestamp, currentowner, currentstatus, nextaction) ";
    $sql .= "VALUES ('{$incidentid}', '{$sit[2]}', 'reassigning', '{$now}', '{$uid}', '1', '{$nextaction}')";
    $result = mysql_query($sql);
    if (mysql_error()) trigger_error("MySQL Query Error ".mysql_error(), E_USER_ERROR);
    include (APPLICATION_INCPATH . 'htmlfooter.inc.php');
	}
}
?>